/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.excel.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.ArrayUtils;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.excel.AbstractExcelRpcExportService;
import com.je.meta.service.ExcelService;
import com.je.meta.service.excel.ExportExcelColumnWidthStyleStrategy;
import com.je.meta.service.excel.ExportExcelVerticalCellStyleStrategy;
import com.je.meta.service.excel.ExportExcelWriteStyleHandler;
import com.je.servicecomb.CommonRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 普通列表导出
 */
@Service("excelRpcGridExportService")
public class ExcelRpcGridExportServiceImpl extends AbstractExcelRpcExportService implements CommonRequestService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private ExcelService excelService;

    @Override
    public InputStream export(JSONObject params, HttpServletRequest request) {
        String funcId = params.getString("funcId");
        //获取数据
        List<DynaBean> datas = getDate(params, request);
        //字段配置信息
        List<DynaBean> columns = metaService.select("je_core_vcolumnandfield",
                ConditionsWrapper.builder().apply(" AND ( RESOURCEFIELD_XTYPE NOT IN ( 'ckeditor' ) OR RESOURCEFIELD_XTYPE IS NULL) " +
                        "AND RESOURCECOLUMN_FUNCINFO_ID='" + funcId + "' AND RESOURCECOLUMN_HIDDEN='0' AND RESOURCECOLUMN_XTYPE NOT IN ('actioncolumn') ORDER BY SY_ORDERINDEX"),
                "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE,RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO");
        //加入多方案后会查出重复字段，需去重，去重规则:若相同字段的类型不同，首选rgroup, cgroup, cbbfield，若相同，取第一个
        delRepeat(columns);
        //封装字典数据
        Map<String, Map<String, String>> ddInfos = excelRpcService.buildDicDatas(columns);
        //获取tile
        List<List<String>> headList = excelRpcService.getReportTile(funcId,params.getString("title"));
        //格式化数据
        List<List<Object>> list = excelService.buildExportData(funcId, datas, ddInfos, columns);
        //初始化输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream).head(headList)
                .registerWriteHandler(new ExportExcelColumnWidthStyleStrategy())
                .registerWriteHandler(new ExportExcelVerticalCellStyleStrategy())
                .registerWriteHandler(new ExportExcelWriteStyleHandler())
                .sheet("sheet1").doWrite(list);
        //输出转输入
        ByteArrayInputStream inputStream = IoUtil.toStream(outputStream.toByteArray());
        IoUtil.close(outputStream);
        return inputStream;
    }

    private void delRepeat(List<DynaBean> columns) {
        List<Integer> indexs = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        for(int i = 0;i<columns.size();i++){
            DynaBean dynaBean = columns.get(i);
            String code = dynaBean.getStr("RESOURCECOLUMN_CODE");
            String type = dynaBean.getStr("RESOURCEFIELD_XTYPE");
            if(map.containsKey(code)){
                if("1".equals(map.get("code"))){
                    indexs.add(i);
                    continue;
                }else {
                    if(ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield"}, type)){
                        String flag =map.get("code").toString();
                        indexs.add(Integer.parseInt(flag.split("_")[1]));
                        map.put(code,"1");
                        continue;
                    }else {
                        indexs.add(i);
                        continue;
                    }
                }
            }
            if(ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield"}, type)){
                map.put(code,"1");
            }else {
                map.put(code,"2"+"_"+i);
            }
        }
        for(Integer integer:indexs){
            columns.remove(integer);
        }
    }


}
